'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  Box,
  Container,
  Typography,
  Paper,
  TextField,
  Button,
  Alert,
  CircularProgress,
  Divider,
  Grid,
  MenuItem,
  Breadcrumbs,
} from '@mui/material';
import Navbar from '@/components/Navbar';

// 行业选项
const INDUSTRY_OPTIONS = [
  '互联网/IT/通信',
  '金融/银行/保险',
  '教育/培训',
  '医疗/健康',
  '房地产/建筑',
  '消费品/零售',
  '制造业',
  '能源/环保',
  '政府/非营利组织',
  '其他',
];

// 公司规模选项
const SIZE_OPTIONS = [
  '少于15人',
  '15-50人',
  '50-100人',
  '100-500人',
  '500-1000人',
  '1000-5000人',
  '5000-10000人',
  '10000人以上',
];

export default function CompanyProfilePage() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [companyInfo, setCompanyInfo] = useState<any>(null);
  const [formData, setFormData] = useState({
    name: '',
    industry: '',
    size: '',
    location: '',
    website: '',
    description: '',
    logo: '',
  });

  useEffect(() => {
    const fetchCompanyInfo = async () => {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          router.push('/auth/login');
          return;
        }

        // 获取用户资料
        const userResponse = await fetch('/api/profile', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (!userResponse.ok) {
          throw new Error('获取用户资料失败');
        }

        const userData = await userResponse.json();
        
        // 检查用户是否是企业管理员
        if (!userData.is_company_admin) {
          router.push('/company/manage');
          return;
        }

        // 获取企业信息
        const companyResponse = await fetch('/api/company/info', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (!companyResponse.ok) {
          throw new Error('获取企业信息失败');
        }

        const companyData = await companyResponse.json();
        setCompanyInfo(companyData);

        // 预填充表单
        setFormData({
          name: companyData.name || '',
          industry: companyData.industry || '',
          size: companyData.size || '',
          location: companyData.location || '',
          website: companyData.website || '',
          description: companyData.description || '',
          logo: companyData.logo || '',
        });
      } catch (err) {
        setError((err as Error).message);
      } finally {
        setLoading(false);
      }
    };

    fetchCompanyInfo();
  }, [router]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setSaving(true);
      setError('');
      setSuccess('');

      const token = localStorage.getItem('token');
      if (!token) {
        router.push('/auth/login');
        return;
      }

      const response = await fetch('/api/company/update', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(formData),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '更新企业资料失败');
      }

      setSuccess('企业资料更新成功');
      setCompanyInfo(data.company);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <>
        <Navbar />
        <Container maxWidth="lg" sx={{ py: 8, textAlign: 'center' }}>
          <CircularProgress />
          <Typography variant="h6" sx={{ mt: 2 }}>
            正在加载企业资料...
          </Typography>
        </Container>
      </>
    );
  }

  return (
    <>
      <Navbar />
      <Box sx={{ bgcolor: 'background.default', minHeight: '100vh', py: 4 }}>
        <Container maxWidth="lg">
          <Box sx={{ mb: 4 }}>
            <Breadcrumbs aria-label="breadcrumb">
              <Link href="/" passHref>
                <Typography color="inherit">首页</Typography>
              </Link>
              <Link href="/company/manage" passHref>
                <Typography color="inherit">企业管理</Typography>
              </Link>
              <Typography color="text.primary">企业资料</Typography>
            </Breadcrumbs>
          </Box>

          <Typography variant="h4" component="h1" gutterBottom>
            编辑企业资料
          </Typography>

          {error && (
            <Alert severity="error" sx={{ mb: 3 }}>
              {error}
            </Alert>
          )}

          {success && (
            <Alert severity="success" sx={{ mb: 3 }}>
              {success}
            </Alert>
          )}

          <Paper sx={{ p: 3 }}>
            <form onSubmit={handleSubmit}>
              <Grid container spacing={3}>
                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="企业名称"
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    required
                  />
                </Grid>

                <Grid item xs={12} md={6}>
                  <TextField
                    fullWidth
                    select
                    label="所属行业"
                    name="industry"
                    value={formData.industry}
                    onChange={handleChange}
                  >
                    {INDUSTRY_OPTIONS.map(option => (
                      <MenuItem key={option} value={option}>
                        {option}
                      </MenuItem>
                    ))}
                  </TextField>
                </Grid>

                <Grid item xs={12} md={6}>
                  <TextField
                    fullWidth
                    select
                    label="公司规模"
                    name="size"
                    value={formData.size}
                    onChange={handleChange}
                  >
                    {SIZE_OPTIONS.map(option => (
                      <MenuItem key={option} value={option}>
                        {option}
                      </MenuItem>
                    ))}
                  </TextField>
                </Grid>

                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="公司地址"
                    name="location"
                    value={formData.location}
                    onChange={handleChange}
                    placeholder="如：北京市海淀区中关村大街1号"
                  />
                </Grid>

                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="公司网站"
                    name="website"
                    value={formData.website}
                    onChange={handleChange}
                    placeholder="如：https://www.example.com"
                  />
                </Grid>

                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="公司Logo URL"
                    name="logo"
                    value={formData.logo}
                    onChange={handleChange}
                    placeholder="输入公司Logo的图片URL"
                    helperText="请输入有效的图片URL，建议使用正方形图片"
                  />
                </Grid>

                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="公司简介"
                    name="description"
                    value={formData.description}
                    onChange={handleChange}
                    multiline
                    rows={6}
                    placeholder="请简要介绍公司的基本情况、业务范围、企业文化等"
                  />
                </Grid>

                <Grid item xs={12}>
                  <Button
                    type="submit"
                    variant="contained"
                    color="primary"
                    size="large"
                    disabled={saving}
                    sx={{ mt: 2 }}
                  >
                    {saving ? <CircularProgress size={24} /> : '保存企业资料'}
                  </Button>
                </Grid>
              </Grid>
            </form>
          </Paper>
        </Container>
      </Box>
    </>
  );
}
